<?php
/**
 * CEOfox
 *
 * @copyright  Copyright 2011-2012 CEOfox, Inc.
 * @license    http://ceofox.com/pages/license
 * @version    $Id: ajax.class.php 17081 2013-05-24 09:40:17 $
 * @author     CEOfox, Inc.
 */
?>
<?php
defined('PHPFOX') or exit('NO DICE!');

class Follow_Component_Ajax_Ajax extends Phpfox_Ajax
{
    private $_aFunction = array();
    public function __construct()
    {            
        $this->_aFunction = array(
          'add' => array('func'  => 'follow'),
          'del' => array('func'  => 'unfollow'),
          'block' => array('func'  => 'block'),
          'unblock' => array('func'  => 'unblock'),
            
        );
    }
    public function viewMore()
    {
        $aParam = array(
            'type_id' => $this->get('module_id'),
            'keyword' => $this->get('keyword'),
            'page' => $this->get('page'),
            'aParentModule' => array(
                'item_id' => $this->get('item_id'),
                'module_id' =>$this->get('module_id'),
            )
        );
        if(Phpfox::getBlock('follow.'.$this->get('type'), $aParam))
        {
            $this->append('#'.$this->get('type').'_'.$this->get('module_id'), $this->getContent(false));
        } 
    }
    /*
    public function viewMore_backup()
    {
        $iPage = $this->get('page');
        $iOffset = ($iPage - 1) * phpfox::getParam('follow.showeachtime');
        $sType = $this->get('type');
        $iItemId = $this->get('item_id');
        $sModule = $this->get('module_id');
        $bIsCurrentUser = false;
        $bIsLogin = (phpfox::getUserId() > 0)? true: false;
        if(!isset($iItemId) || ($iItemId == phpfox::getUserId()))
        {
            $iItemId = phpfox::getUserId();
            $bIsCurrentUser = true;
        }
        switch($sType)
        {
            case 'following':
                $aFollowings = phpfox::getService('follow')->getFollowing($iItemId, $iOffset, Phpfox::getParam('follow.showeachtime'), $sModule);
                $aResult = array();  
                foreach($aFollowings as $aFollowing)
                {
                    $aTemp = phpfox::getservice('user')->get($aFollowing['user_id']);
                    if($aFollowing['user_id'] == $iItemId)
                    {
                        $aTemp['canFollow'] = 0;
                        $aTemp['isFollow'] = 0;
                    }
                    else
                    {
                        if(Phpfox::getService('follow')->canFollow($aFollowing['user_id']))
                        {
                            if(phpfox::getService('follow')->isFollow($aFollowing['user_id']) == 0)
                            {
                                $aTemp['isFollow'] = 0;
                            }
                            else
                            {
                                $aTemp['isFollow'] = 1;
                            }
                            $aTemp['canFollow'] = 1;
                        }
                        else
                        {   
                            $aTemp['isFollow'] = 0;
                            $aTemp['canFollow'] = 0;
                        }
                    }
                    $aResult[] = $aTemp;
                }
                if(count($aResult) == "")
                {
                    $this->call('$Core.follow.hideViewMore("'.$sType.'");');
                }
                $this->call('$Core.follow.updateCurrent(\'following\','.count($aResult).');');
                $sHTML = phpfox::getLib('template')->assign(array(
                    'aFollowings' => $aResult,
                    'bIsCurrentUser' => $bIsCurrentUser,
                    'bIsLogin' => $bIsLogin)
                )
                ->getTemplate('follow.block.'.$sType,true);
                $sHTML = $this->prepareHtml($sHTML);
                $this->call('$("#following").append("'.$sHTML.'");');
                break;
            case 'follower':

                $aFollowers = phpfox::getService('follow')->getFollower($iItemId, $iOffset, phpfox::getParam('follow.showeachtime'));
                $aResult = array();  
                foreach($aFollowers as $aFollower)
                {
                    $aTemp = phpfox::getservice('user')->get($aFollower['follower_id']);
                    if($aFollower['follower_id'] == $iItemId)
                    {
                        $aTemp['canFollow'] = 0;
                        $aTemp['isFollow'] = 0;
                    }
                    else
                    {
                        if(Phpfox::getService('follow')->canFollow($aFollower['follower_id']))
                        {
                            if(phpfox::getService('follow')->isFollow($aFollower['follower_id']) == 0)
                            {
                                $aTemp['isFollow'] = 0;
                            }
                            else
                            {
                                $aTemp['isFollow'] = 1;
                            }
                            $aTemp['canFollow'] = 1;
                        }
                        else
                        {   
                            $aTemp['isFollow'] = 0;
                            $aTemp['canFollow'] = 0;
                        }
                    }
                    $aResult[] = $aTemp;
                }
                
                if(count($aResult) == "")
                {
                    $this->call('$Core.follow.hideViewMore("'.$sType.'");');
                }
                $this->call('$Core.follow.updateCurrent(\'follower\','.count($aResult).');');
                $sHTML = phpfox::getLib('template')->assign(array(
                    'aFollowers' => $aResult,
                    'bIsCurrentUser' => $bIsCurrentUser,
                    'bIsLogin' => $bIsLogin)
                )
                ->getTemplate('follow.block.'.$sType,true);
                $sHTML = $this->prepareHtml($sHTML);
                $this->call('$("#follower").append("'.$sHTML.'");');
                break;
            case 'blocker':
                $aBlockers = phpfox::getService('follow')->getBlocker($iItemId, $iOffset, 2);
                $aResult = array();  
                foreach($aBlockers as $aBlocker)
                {
                    $aTemp = phpfox::getservice('user')->get($aBlocker['blocker_id']);
                    $aResult[] = $aTemp;
                }
                if(count($aResult) == "")
                {
                    $this->call('$Core.follow.hideViewMore("'.$sType.'");');
                }
                $this->call('$Core.follow.updateCurrent(\'blocker\','.count($aResult).');');
                $sHTML = phpfox::getLib('template')->assign(array(
                    'aBlockers' => $aResult)
                )
                ->getTemplate('follow.block.'.$sType,true);
                $sHTML = $this->prepareHtml($sHTML);
                $this->call('$("#blocker").append("'.$sHTML.'");');
                break;
        }
        $iPage++;
        $this->call('$Core.follow.setPage('.$iPage.',"'.$sType.'");');
 
    }*/
    public function reloadNotification()
    {
        Phpfox::isUser();
        $iNewestId = $this->get('newest-id', 0);
        if(Phpfox::getBlock('follow.notifications', array('newest-id' => $iNewestId, 'reload' => true)))
        {
            $iNewestId = Phpfox::getService('follow.notifications')->getNewestId(Phpfox::getUserId());
            $sHtml = $this->getContent(false);
            $this->call('$Core.follow.updateNotification('.$iNewestId.', \''.$sHtml.'\');');
        }
        
        $this->call('setTimeout("$.ajaxCall(\'follow.reloadNotification\', \'newest-id=\' + $Core.follow.getNewestId(), \'GET\');", ' . (Phpfox::getParam('follow.refresh_notification') * 1000).');'); 
        
    }
    public function confirmFollow()
    {
        $iUserId = $this->get('user_id', false);
        $iNotiId = $this->get('noti_id', false);
        $iItemId = $this->get('item_id', false);
        $sType = $this->get('type', false);
        if(!$iUserId || !$iNotiId || !$sType || !$iItemId)
        {
            return false;
        }
        if(Phpfox::getService('follow')->isFollow($iUserId, $iItemId, $sType))
        {
            
            $this->call('$(\'#js_notification_read_'.$iNotiId.'\').slideUp();');
            Phpfox::getLib('database')->delete(Phpfox::getT('notification'),'notification_id = '.(int)$iNotiId);
            return true;    
        }  
           
        if(Phpfox::getService('follow')->followAfterConfirm($iItemId, $sType, $iUserId))
        {
            if(Phpfox::getLib('database')->delete(Phpfox::getT('notification'),'notification_id = '.(int)$iNotiId))
            {
                $this->call('$(\'#js_notification_read_'.$iNotiId.'\').slideUp();');
                return true;    
            }
        }
        Phpfox_Error::set(Phpfox::getPhrase('follow.there_are_some_errors_happen_when_follow_this_user'));
        return false;
    }
    
    public function denyFollow()
    {
        $iUserId = $this->get('user_id', false);
        $iNotiId = $this->get('noti_id', false); 
        $iItemId = $this->get('item_id', false);
        $sType = $this->get('type', false);
        if(!$iUserId || !$iNotiId || !$sType || !$iItemId)
        {
            return false;
        }
        if(Phpfox::getService('follow')->denyFollow($iItemId, $sType, $iUserId))
        {
            if(Phpfox::getLib('database')->delete(Phpfox::getT('notification'),'notification_id = '.(int)$iNotiId))
            {
                $this->call('$(\'#js_notification_read_'.$iNotiId.'\').slideUp();');
                return true;
            }
        }
        Phpfox_Error::set(Phpfox::getPhrase('follow.there_are_some_errors_happen_when_deny_this_user_follow_you'));
        return false;
    }
    
    public function confirmFollowIndex()
    {
        $iUserId = $this->get('user_id', false);
        $iPendingId = $this->get('pending_id', false);
        $iItemId = $this->get('item_id', false);
        $sType = $this->get('type', false);
        if(!$iUserId || !$iPendingId || !$sType || !$iItemId)
        {
            return false;
        } 
        
        if(Phpfox::getService('follow')->followAfterConfirm($iItemId, $sType, $iUserId))
        {
            if(Phpfox::getLib('database')->delete(Phpfox::getT('notification'),'type_id = "follow_waiting_item" AND item_id = '.(int)$iPendingId))
            {
                $this->call('$(\'#js_pending_'.$iPendingId.'\').slideUp();');
                return true;    
            }
        }
        Phpfox_Error::set(Phpfox::getPhrase('follow.there_are_some_errors_happen_when_follow_this_user'));
        return false;
    }
    public function changeApproval()
    {
        $iStatus = $this->get('status', 0);
        $iItemId = $this->get('item_id', 0);
        $sType = $this->get('type', 0);
        if(!$sType || !$iItemId)
        {
            return false;
        }
        if(Phpfox::getService('follow.process')->changeApproval($iItemId, $iStatus, $sType))
        {
            $sUrl = Phpfox::getLib('url')->makeUrl('follow.pending');
            $this->call('window.location.href = "'.$sUrl.'";');
        }
        else
        {
            Phpfox_Error::set(Phpfox::getPhrase('follow.there_are_some_errors_happen_when_change_approval'));
            return false;
        }
    }
    public function denyFollowIndex()
    {
        $iUserId = $this->get('user_id', false);
        $iPendingId = $this->get('pending_id', false); 
        $iItemId = $this->get('item_id', false);
        $sType = $this->get('type', false);
        if(!$iUserId || !$iPendingId)
        {
            return false;
        }
        if(Phpfox::getService('follow')->denyFollow($iItemId, $sType, $iUserId))
        {
            if(Phpfox::getLib('database')->delete(Phpfox::getT('notification'),'type_id = "follow_waiting_item" AND item_id = '.(int)$iPendingId))
            {
                $this->call('$(\'#js_pending_'.$iPendingId.'\').slideUp();');
                return true;
            }
        }
        Phpfox_Error::set(Phpfox::getPhrase('follow.there_are_some_errors_happen_when_deny_this_user_follow_you'));
        return false;
    }
    
    public function prepareHtml($sHTML)
    {
        $sHTML = str_replace(array("\n", "\t"), '', $sHTML);          
        $sHTML = str_replace('\\', '\\\\', $sHTML);
        $sHTML = str_replace("'", "\\'", $sHTML);            
        $sHTML = str_replace('"', '\"', $sHTML);
        return $sHTML;
    }
    
    public function viewMoreFeed()
    {
        Phpfox::getBlock('follow.display');        
        $this->remove('#feed_view_more');
        $this->append('#js_feed_content', $this->getContent(false));
        $this->call('$Core.loadInit();');
    }
    
    public function follow($aParam = array())
    {
        $iId = $aParam['id'];
        $sType = $aParam['type'];
        $iItemId = $aParam['oid'];
        
        if(!$iId || !$iItemId || !$sType)
        {
            return false;
        }
        $sMessage = '';
        if(phpfox::getUserId() == $iId && $sType == 'user')
        {
            $sMessage =  Phpfox::getPhrase('follow.you_can_not_follow_yourself');        
        }
        if(phpfox::getService('follow')->canFollow($iItemId, $sType))
        {
            if(!Phpfox::getService('follow')->isFollow($iId, $iItemId, $sType))
            {
                if(phpfox::getService('follow')->follow($iItemId, $sType))
                {
                    $sMessage =  Phpfox::getPhrase('follow.follow_successfully');
                    $this->call('$(\'.follow_'.$sType.'_'.$iItemId.'\').hide();');
                    $this->call('$(\'.unfollow_'.$sType.'_'.$iItemId.'\').show();');
                    /**
                     * @author tantrinh
                     * backup
                     * //$this->call('tb_show(\''.Phpfox::getPhrase('follow.follow_setting').'\', $.ajaxBox(\'follow.setting\',\'width=400&type='.$sType.'&id='.$iId.'&oid='.$iItemId.'\'));');
                     */
                    
                }
                else
                {
                    $sMessage =  Phpfox::getPhrase('follow.user_id_not_exists');
                } 
            }
            else
            {
                $sMessage =  phpfox::getPhrase('follow.you_already_followed_this_user');
            }
        }
        else
        {
            $sMessage =  Phpfox::getPhrase('follow.you_can_not_follow_this_user');    
        }
        
        $this->alert($sMessage);
    }
    public function unfollow($aParam = array())
    {
        $iId = $aParam['id'];
        $sType = $aParam['type'];
        $iItemId = $aParam['oid'];

        if(!$iId || !$iItemId || !$sType)
        {
            return false;
        }
        $sMessage = '';
        if(Phpfox::getUserId() == $iItemId && $sType == 'user')
        {
              $sMessage = Phpfox::getPhrase('follow.you_can_not_unfollow_yourself');
        }
        if(Phpfox::getService('follow')->isUserExists($iId))
        {
              if(Phpfox::getService('follow')->isFollow($iId, $iItemId, $sType))
              {
                  if(Phpfox::getService('follow')->unFollow($iItemId, $iId, $sType))
                  {
                      $sMessage = Phpfox::getPhrase('follow.unfollow_successfully');
                      $this->call('$(\'.follow_'.$sType.'_'.$iItemId.'\').show();');
                      $this->call('$(\'.unfollow_'.$sType.'_'.$iItemId.'\').hide();');
                  }
                  else
                  {
                      $sMessage = Phpfox::getPhrase('follow.user_id_not_exists');
                  }
              }
              else
              {
                  $sMessage = Phpfox::getPhrase('follow.you_havent_followed_this_user_yet');
              }
        }
        else
        {
            $sMessage =  Phpfox::getPhrase('follow.user_id_not_exists');
        }
        
        $this->alert($sMessage);
    }
    public function setting()
    {
        $iId = $this->get('id');
        $sType = $this->get('type');
        $iItemId = $this->get('oid');
        if(!$iId || !$iItemId || !$sType)
        {
            return false;
        }
        $sMessage = '';
        $aParentModule = array(
            'item_id' => $iItemId,
            'module_id' => $sType
        );
        Phpfox::getBlock('follow.setting', array(
            'sType' => $sType,
            'aParentModule' => $aParentModule,
        ));
    }
    
    public function block($aParam = array())
    {
        $iId = $aParam['id'];
        $sType = $aParam['type'];
        $iItemId = $aParam['oid'];
        if(!$iId || !$iItemId || !$sType)
        {
            return false;
        }
        $sMessage = '';
        if(phpfox::getUserId() == $iItemId && $sType == 'user')
        {
            $sMessage = Phpfox::getPhrase('follow.you_can_not_block_yourself');      
        }
        if(Phpfox::getService('follow')->isUserExists($iId))
        {
            if(!Phpfox::getService('follow')->alreadyBlock($iItemId, $iId, $sType) && $iId > 0)
            {
                if(Phpfox::getService('follow')->blockUser($iItemId, $iId, $sType))
                {
                    $sMessage = Phpfox::getPhrase('follow.block_follow_successfully');        
                    $this->call('$(\'.block_'.$sType.'_'.$iId.'\').hide();');
                    $this->call('$(\'.unblock_'.$sType.'_'.$iId.'\').show();');
                }
                else
                {
                    $sMessage = Phpfox::getPhrase('follow.there_are_some_errors_happen_when_block_this_user');
                }

            }
            else
            {
                $sMessage = Phpfox::getPhrase('follow.you_already_blocked_this_user');    
            }    
        }
        else
        {
            $sMessage = Phpfox::getPhrase('follow.user_id_not_exists');
        }
        $this->alert($sMessage);
    }
    public function changeSetting()
    {
        $aVals = (array) $this->get('val');
        
        $oFollow = Phpfox::getService('follow');        
        if($oFollow->setFilter(Phpfox::getUserId(), $aVals['item_id'], $aVals['module_id'], $aVals))
          {
              if(isset($aVals['is_ajax']) && $aVals['is_ajax'] == false)
              {
                  $this->call('window.location.href = window.location.href;');
              }   
              else
              {
                  $this->call('tb_remove();');
              }               
          }
          else
          {
              if(isset($aVals['is_ajax']) && $aVals['is_ajax'] == false)
              {
                  $this->call('window.location.href = window.location.href;');
              }
              else
              {
                  $this->call('tb_remove();');
              }
          }
    }
    public function unblock($aParam = array())
    {
        $iId = $aParam['id'];
        $sType = $aParam['type'];
        $iItemId = $aParam['oid'];
        if(!$iId || !$iItemId || !$sType)
        {
            return false;
        }
        $sMessage = '';     
        if(phpfox::getUserId() == $iId && $sType == 'user')
        {
            $sMessage = Phpfox::getPhrase('follow.you_can_not_unblock_yourself');      
        }
        if(Phpfox::getService('follow')->isUserExists($iId))
        {
            if(Phpfox::getService('follow')->alreadyBlock($iItemId, $iId, $sType) && $iId > 0)
            {
                if(Phpfox::getService('follow')->unBlock($iItemId, $iId, $sType))
                {
                    $sMessage =  Phpfox::getPhrase('follow.unblock_successfully');      
                    $this->call('$(\'.unblock_'.$sType.'_'.$iId.'\').hide();');
                    $this->call('$(\'.block_'.$sType.'_'.$iId.'\').show();');
                }
                else
                {
                    $sMessage = Phpfox::getPhrase('follow.there_are_some_errors_happen_when_perform_this_action'); 
                }
            }
            else
            {
                $sMessage =  Phpfox::getPhrase('follow.you_havent_blocked_this_user_yet');   
            }
        }
        else
        {
            $sMessage =  Phpfox::getPhrase('follow.user_id_not_exists');
        }
        $this->alert($sMessage);
    }
    public function parseFunction()
    {
        $sUrl = $this->get('url', false);
        $sUrl = str_replace('/index.php?do=','',$sUrl);
        $sController = $this->get('controller', false);
        $bIsTrigger = (isset($sController) && ( $sController == 'profile.index' || $sController == 'follow.index')) ? true: false;
        if(empty($sUrl))
        {
            return false;
        }
        $sPattern = "/\/follow\/(?P<func>\w+)\//i";
        preg_match($sPattern, $sUrl,$aMatches);
        if(!isset($aMatches['func']) && !empty($aMatches['func']))
        {
            return false;
        }
        $sFunction = $aMatches['func'];
        $aUrl = parse_url($sUrl);
       
        $aPart = explode('/', $aUrl['path']);
        $aParam = array();
        for($i = 0; $i <= count($aPart); $i++)
        {
            if(isset($aPart[$i]) && !empty($aPart[$i]))
			{
				$aTemp = explode('_', $aPart[$i]);
				if(isset($aTemp[0]) && count($aTemp) == 2)
				{
					$aParam[$aTemp[0]] = $aTemp[1];
				}
			}
            
        }
        $aParam['trigger'] = $bIsTrigger;
        if(!empty($sFunction) && !empty($aParam))
        {
            
            return call_user_func_array(array($this, $this->_aFunction[$sFunction]['func']), array($aParam));    
        }
        return false;       
        
    }
}

?>
